<?php
namespace app\api\controller;

use app\common\model\Forum as ForumModel;
use app\common\model\Reply as ReplyModel;
use app\common\validate\Reply as ReplyValidate;

class Reply extends Base
{
	public function initialize()
	{
		parent::initialize();
		if((request()->action() != 'index') && !$this->user){
			return cdm(401,0,'请先登录!');
		}
	}

	public function index()
	{
		$page = request_input('page',1);
		$param['forum_id'] = request_input('forum_id',0);

		if(empty($param['forum_id'])){
			return cdm(500, 0, '数据不存在');
		}

		$data = ReplyModel::Nwhere($param)->paginate(10)->append(['user']);
		return cdm(200, $data, '');
	}

	public function create()
	{
		$page = request_input('page',1);
		$data = $this->user->replys()->order('id desc')->paginate(10);
		return cdm(200, $data, '');
	}

	public function save()
	{
		$data['forum_id'] = request_input('forum_id',0);
		$data['content'] = request_input('content','');

		$validate = new ReplyValidate;
		if (!$validate->check($data)) {
			return cdm(500, 0, $validate->getError());
		}

		$forum = ForumModel::get($data['forum_id']);
		if(!$forum){
			return cdm(500, 0, '主题不存在!');
		}

		$this->user->replys()->save($data);
		$forum->save(['reply_count'=>$forum->reply_count + 1,'reply_time'=>time()]);
		return cdm(200, 1, '回复成功!');
	}

	public function read($id)
	{
		$data = $this->user->replys()->get($id);
		if($data){
			return cdm(200, $data, '');
		}else{
			return cdm(500, 0, '数据不存在');
		}
	}

	public function edit($id)
	{
		
	}

	public function update($id)
	{
		$data['content'] = request_input('content','');

		$validate = new ReplyValidate;
		if (!$validate->check($data)) {
			return cdm(500, 0, $validate->getError());
		}

		$reply = $this->user->replys()->get($id);
		if(!$reply){
			return cdm(500, 0, '数据不存在!');
		}
		$reply->save($data);
		return cdm(200, 1, '修改成功!');
	}

	public function delete($id)
	{
		$reply = $this->user->replys()->get($id);
		if(!$reply){
			return cdm(500, 0, '数据不存在!');
		}
		$ret = $reply->destroy($id);
		if($ret){
			return cdm(200, 1, '删除成功!');
		}
		return cdm(500, 0, '删除失败!');
	}
}